#!/bin/bash
#
# fxworker      This shell script takes care of starting and stopping
#               fxworker (on 8002)
#
#
# chkconfig: 2345 99 20

# Source function library.
. /etc/init.d/functions
. /root/hack_hostname.sh

getpid() {
  echo `ps -ef|grep -w $PORT|grep -v grep|awk '{printf $2}'`
}

FXWORKER_DIR=/opt/pcs-server/pcs-server/WEB-INF
PIDFILE=/var/run/fxworker.pid
prog=fxworker
PORT=8002
PID=`getpid`

# "Spring Profile Options", invoking the process with correct parameter, "dev" under Vagrant
SPRING_PROFILE_OPTS=--spring.profiles.active=prod,worker
LOG_PATH=/mnt/pcslog

MY_CLASSPATH=$FXWORKER_DIR/classes:$JAVA_HOME/lib/rt.jar:$JAVA_HOME/lib/dt.jar

if [ -z $PID ] && [ -e ${PIDFILE} ]; then
  rm ${PIDFILE}
fi

if [ -z $PID ] && [ -e /var/lock/subsys/$prog ]; then
  rm -f /var/lock/subsys/$prog
fi

start() {
#	if lsmod | grep -q vboxsf; then
	PC_ENV=`echo ${HOSTNAME}|awk -F '.' '{print $3}'`
	if [[ ${PC_ENV} = 'foxitcloud' ]] ; then
		echo "Staring service under Vagrant..."
		SPRING_PROFILE_OPTS=--spring.profiles.active=dev,worker
		LOG_PATH=/var/log
	else
		echo "Starting service under non-Vagrant env..."
	fi
	
	PID=`getpid`

	if [ $PID ]; then
                echo Foxit Worker Server already running.
        else
		echo "begin to load jar"
		for jar in `ls ${FXWORKER_DIR}/lib/*.jar`
		do
       		 MY_CLASSPATH="$MY_CLASSPATH":"$jar"
		done
		# THis special variable will be picked up by Java
		export CLASSPATH=${MY_CLASSPATH}

                cd $FXWORKER_DIR
		# No need to put CLASSPATH on the command line because we exported it above
              java -Xmx2560m -Xms512m -XX:PermSize=512m -XX:MaxPermSize=512m -XX:NewRatio=4 -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log -XX:ErrorFile=./stderr -XX:+UseConcMarkSweepGC com.foxitcloud.Application --server.port=$PORT ${SPRING_PROFILE_OPTS} --logging.file=${LOG_PATH}/fxworker.log >/dev/null 2>&1 &
              #  java -Xms200M -Xmx1024M -XX:PermSize=64M -XX:MaxPermSize=128M com.foxitcloud.Application --server.port=$PORT ${SPRING_PROFILE_OPTS} --logging.file=/var/log/fxworker.log >/dev/null 2>&1 &
		echo $! > ${PIDFILE}
                RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
	    	  action $"Starting $prog: " /bin/true
	    	  touch /var/lock/subsys/$prog
		else
	    	  action $"Starting $prog: " /bin/false
		fi
                return $RETVAL
        fi

}

stop() {
	PID=`getpid`
	if [ -z $PID ]; then
	  echo "Foxit Worker Server already stopped"
	else
          kill -9 $PID
          action $"Stopping $prog: " /bin/true
	fi
        rm -f /var/lock/subsys/$prog ${PIDFILE}
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status -p ${PIDFILE} $prog
        ;;
    restart)
        stop
	sleep 8
        start
        ;;
    *)
        echo "Usage:  {start|stop|status|restart}"
        exit 1
        ;;
esac
exit $?
